<?php
declare (strict_types = 1);

namespace app\common\libs\module;

use app\admin\controller\Menu;
use app\admin\model\AccessModel;
use app\admin\model\MenuModel;
use app\admin\model\ModuleModel;
use app\admin\service\BaseService;
use app\common\libs\helper\FileHelper;
use think\facade\Db;

/**
 * 模块卸载
 *
 * @Author tanruizheng
 * @DateTime 2021-07-30
 */
class ModuleUninstall extends BaseService
{

    private $module;

    public function __construct($module)
    {
        $this->module = $module;
    }

    /**
     * 执行模块卸载
     *
     * @Author tanruizheng
     * @DateTime 2021-07-30
     * @return void
     */
    public function run(){
        $module = $this->module;
        //设置脚本最大执行时间
        set_time_limit(0);
        //删除安装记录
        ModuleModel::where('module',$module)->delete();
        //执行sql语句卸载
        $ModuleInstall = new ModuleInstall($module);
        $ModuleInstall->runSql($module, 'uninstall');
        //执行菜单栏卸载
        $this->unInstallMenu($module);
        //执行静态资源卸载
        $path = public_path().'/static/extra/'. strtolower($module);
        $FileHelper = new FileHelper();
        $FileHelper->deleteDir($path);
        return self::createSuccess('卸载完成');
    }

    /**
     * 菜单栏卸载
     *
     * @Author tanruizheng
     * @DateTime 2021-08-02
     * @param [type] $module
     * @return void
     */
    public function unInstallMenu($module){
        Db::startTrans();
        try {
            MenuModel::where('app',$module)->delete();
            AccessModel::where('app',$module)->delete();
            Db::commit();
            return self::createSuccess('菜单卸载成功');
        } catch (\Exception $e) {
            Db::rollback();
            return self::createFail($e->getMessage());
        }
       
    }
}
